<?php

/**
 * Description of RepositoryLoader
 *
 * Copyright (c) 2011 Tomáš Holub (tomas.holub@webadvice.cz)
 * 
 * @author Tomáš Holub (tomas.holub@webadvice.cz)
 * @package OverFishCMS
 */

namespace OverFish\Services;

use Nette\DI\Container;

final class RepositoryLoader {
    
    /** @var Nette\DI\Container */
    private $repositoryContainer;

    /** @var array */
    private $repositories = array();
    
    public function __construct(Container $container)
    {
        $modelContainer = new Container;
        $modelContainer->addService('database', $container->database);
        $modelContainer->addService('cacheStorage', $container->cacheStorage);
        $modelContainer->addService('session', $container->session);
        $modelContainer->params = $container->params['repositoryMappers'];
        $modelContainer->freeze();
        $this->repositoryContainer = $modelContainer;
    }
    
    public function getRepository($name)
    {
        $lname = strtolower($name);

        if (!isset($this->repositories[$lname])) {
            $class = 'OverFish\\Model\\Repositories\\' . ucfirst($name);

            if (!class_exists($class)) {
                throw new \InvalidArgumentException("Repository '$class' not found");
            }

            $mapper = new $this->repositoryContainer->params[ucfirst($name)]($this->repositoryContainer->database);
            
            $this->repositories[$lname] = new $class($this->repositoryContainer, $mapper);
        }

        return $this->repositories[$lname];
    }

    public function __get($name)
    {
        return $this->getRepository($name);
    }
}

